package com.wisenet.wx.tenpay.http.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class XMLUtil {
	/**
	 * 解析xml，返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据
	 * @param strxml
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes" })
	public static SortedMap<String, String> doXMLParse(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) return null;
		
		SAXBuilder builder = new SAXBuilder();
		// 防范XML外部实体注入漏洞
		builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
		builder.setFeature("http://xml.org/sax/features/external-general-entities", false);
		builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
		
		// 转换流
		InputStream inputStream = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		Element root = builder.build(inputStream).getRootElement();
		Iterator iterator = root.getChildren().iterator();
		
		// 组装map
		SortedMap<String, String> map = new TreeMap<String, String>();
		while (iterator.hasNext()) {
			Element e = (Element) iterator.next();
			String value = "";
			String key = e.getName();
			List children = e.getChildren();
			if (children.isEmpty()) {
				value = e.getTextNormalize();
			} else {
				value = getChildrenText(children);
			}
			map.put(key, value);
		}
		inputStream.close();
		return map;
	}
	
	/**
	 * 获取子节点的xml
	 * @param children
	 * @return String
	 */
	@SuppressWarnings("rawtypes")
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<").append(name).append(">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</").append(name).append(">");
			}
		}
		return sb.toString();
	}

	/**
     * @Description：将请求参数转换为xml格式的string
     * @param parameters  请求参数
     * @return
     */
    @SuppressWarnings("rawtypes")
	public static String getRequestXml(SortedMap<String,String> parameters){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String key = (String)entry.getKey();
            String value = (String)entry.getValue();
			if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
				sb.append("<").append(key).append(">")
				  .append("<![CDATA[").append(value).append("]]>")
				  .append("</").append(key).append(">");
			} else {
				sb.append("<").append(key).append(">")
				  .append(value).append("</").append(key).append(">");
			}
        }
        sb.append("</xml>");
        return sb.toString();
    }
}
